package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type voice struct {
	iVoice store.IVoice
}

var Voice = &voice{
	iVoice: postgres.Voice,
}

func (a *voice) init() func() {
	return func() {}
}

func (a *voice) onEvent(*event.Data) {}

// Create 创建
func (a *voice) Create(ctx context.Context, in *model.VoiceCreateRequest) error {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildVoice(in)
	_, err = a.iVoice.Create(ctx, c)
	return err
}

// Update 更新
func (a *voice) Update(ctx context.Context, in *model.VoiceUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.Name != nil {
		dict["name"] = in.Name
	}

	if in.Url != nil {
		dict["url"] = in.Url
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here

	return a.iVoice.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *voice) Delete(ctx context.Context, in *model.VoiceDeleteRequest) error {
	return a.iVoice.Delete(ctx, in.Id)
}

// List 列表查询
func (a *voice) List(ctx context.Context, in *model.VoiceListRequest) (*model.VoiceListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Voice
		out   = &model.VoiceListResponse{}
	)

	if total, list, err = a.iVoice.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.VoicesEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *voice) Find(ctx context.Context, in *model.VoiceInfoRequest) (*model.VoiceInfo, error) {
	var (
		err  error
		data *entity.Voice
		out  = &model.VoiceInfo{}
	)

	if data, err = a.iVoice.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.VoiceEntityToDto(data)
	return out, nil
}

// buildVoice 构建创建数据现场
func buildVoice(in *model.VoiceCreateRequest) *entity.Voice {
	// todo: check the entity is required
	return &entity.Voice{

		Name: in.Name,

		Url: in.Url,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
